//
//  GoogleMapXmlDataParser.m
//  FleaFinder
//
//  Created by Hieu Le on 4/13/13.
//  Copyright (c) 2013 Kiwiweb. All rights reserved.
//

#import "GoogleMapXmlDataParser.h"

@implementation GoogleMapXmlDataParser

@synthesize lat;
@synthesize lng;

-(id) init
{
    self = [super init];
    if(self != nil){
        tagLat = @"lat";
        tagLng = @"lng";
        tagLocaltion = @"location";
        
        isInsideTagLocation = NO;
        currentTag = -1;
    }
    return self;
}

-(void) parseXML:(NSString *)sourceUrl
{
    NSURL *url = [NSURL URLWithString:sourceUrl];
    NSData* data =  [NSData dataWithContentsOfURL:url];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    [xmlParser setDelegate:self];
    [xmlParser parse];
}

#pragma implementation of NSXMLParserDelegate

-(void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{

}

-(void) parserDidStartDocument:(NSXMLParser *)parser
{
    //NSLog(@"Start the document");
}

-(void) parserDidEndDocument:(NSXMLParser *)parser
{
    //NSLog(@"End the document");
}

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    //static NSString *currentMarkedType = nil;
    
    ///NSLog(@"Start element name: %@", elementName);
    //NSLog(@"value of attribute NAME: %@", [attributeDict objectForKey:@"name"]);
    
    if ([tagLocaltion compare:elementName] == NSOrderedSame) {
        currentTag = ADD_TAG_LOCATION;
        isInsideTagLocation = YES;
    } else if([tagLat compare:elementName] == NSOrderedSame){
        currentTag = ADD_TAG_LAT;
    } else if([tagLng compare:elementName] == NSOrderedSame){
        currentTag = ADD_TAG_LNG;
    }
    
}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    currentTag = -1;
    //NSLog(@"End element name: %@", elementName);
    if([tagLocaltion compare:elementName] == NSOrderedSame)
    {
        isInsideTagLocation = NO;
    }
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //NSLog(@"Character: %@", string);
    
    if(isInsideTagLocation && currentTag == ADD_TAG_LAT){
        lat = [string doubleValue];
    } else if(isInsideTagLocation && currentTag == ADD_TAG_LNG){
        lng = [string doubleValue];
    }
}

@end
